<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/params' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert class="alert" title="只能选择三级列表" type="warning" show-icon>
      </el-alert>
      <el-row>
        <el-col>
          <span> 选择商品分类: </span>
          <el-cascader
            expand-trigger="hover"
            :options="catalist"
            v-model="selectCateId"
            :props="cataListProps"
            @change="handleChange"
            style="width: 250px"
          >
          </el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加动态参数</el-button
          >

          <!-- 动态参数 -->
          <el-table :data="manyDataList" style="width: 100%" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="tagClosed(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialogVisible(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加静态属性</el-button
          ><!-- 静态参数 -->
          <el-table :data="onlyDataList" style="width: 100%" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="tagClosed(i, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialogVisible(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'修改' + textLable"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editFormClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="textLable" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 共用对话框 -->
    <el-dialog
      :title="'添加' + textLable"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="textLable" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      catalist: [],
      selectCateId: [],
      cataListProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      activeName: "many",
      manyDataList: [],
      onlyDataList: [],
      addDialogVisible: false,
      addForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCataList();
  },
  methods: {
    async getCataList() {
      const { data: res } = await this.$http.get("categories");

      if (res.meta.status !== 200) {
        this.$message.error("获取数据失败");
      }

      this.catalist = res.data;
    },
    // 选中的时候
    handleChange() {
      // console.log(this.selectCateId);
      this.getParamsData();
    },
    // 点击变换Tab的时候
    handleTabClick() {
      console.log(this.activeName);
      this.getParamsData();
    },

    //拿到第三列的数据
    async getParamsData() {
      if (this.selectCateId.length !== 3) {
        this.selectCateId = [];
        this.manyDataList = [];
        this.onlyDataList = [];
        return;
      }
      console.log(this.selectCateId);
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取信息失败");
      }
      // 使attr_vals分隔开
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      // console.log(res.data);
      if (this.activeName === "many") {
        this.manyDataList = res.data;
      }
      this.onlyDataList = res.data;

      console.log(res.data);
    },

    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //添加参数 确定
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加参数失败！");
        }
        this.$message.success("添加参数成功");
        this.addDialogVisible = false;
        this.getParamsData();
      });
    },
    // new tag失去焦点 或按了回车
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        //空白字符串无效
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }

      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;

      this.saveVal(row);
    },
    async saveVal(row) {
      //保存newTag的修改
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("修改错误");
      }
      this.$message.success("修改成功");
    },

    showInput(row) {
      row.inputVisible = true;
      //页面重新渲染时执行这个函数
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    tagClosed(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveVal(row);
    },
    async showEditDialogVisible(rowId) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${rowId}`,
        {
          params: { attr_sel: this.activeName },
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("获取信息失败");
      }
      this.editForm = res.data; //直接赋值
      this.editDialogVisible = true;
      console.log(this.editForm);
    },
    editFormClosed() {
      this.$refs.editFormRef.resetFields();
    },

    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const {
          data: res,
        } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败");
        }
        this.$message.success("修改成功");
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    async removeParams(rowId) {
      const removeResult = await this.$confirm("确认删除这个参数吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err);

      if (removeResult !== "confirm") {
        return this.$message.info("删除取消");
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${rowId}`
      );

      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }

      this.$message.success("删除成功");
      this.getParamsData();
    },
  },
  computed: {
    isBtnDisabled() {
      if (this.selectCateId.length !== 3) {
        return true;
      }
      return false;
    },
    // 获取第三列的ID
    cateId() {
      if (this.selectCateId.length === 3) {
        return this.selectCateId[2];
      }
      return null;
    },
    textLable() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态参数";
    },
  },
};
</script>

<style scoped>
.alert {
  margin-bottom: 15px;
}
.el-tag {
  margin: 0 10px;
}
.el-input {
  width: 150px;
}
</style>